package com.y.mytest.jm;

import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.RandomUtil;

import java.security.DigestException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;

public class Sha1 {

    public static void main(String[] args) throws DigestException {
        Map<String, Object> map = new HashMap<String, Object>() {{
            put("noncestr", "he9jju1h8lbd1im2");
            put("jsapi_ticket", "LIKLckvwlJT9cWIhEQTwfJ9cUmcz5Y_B31tu7ajWF6o4o3BSv8HZPtyWf4N6rrXnVDphiHXtgYnBbbAJKN1sFg");
            put("timestamp", 1671592289);
            put("url", "http://ums.dikeni.com:4538/informant");
        }};
        System.out.println(getOrderSHA1(map));
        System.out.println(getSHA1("jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW&timestamp=1414587457&url=http://mp.weixin.qq.com?params=value"));
    }

    /**
     * SHA1 安全加密算法
     *
     * @param maps 参数key-value map集合
     * @return
     * @throws DigestException
     */
    public static String getOrderSHA1(Map<String, Object> maps) throws DigestException {
        //获取信息摘要 - 参数字典排序后字符串
        List<String> keys = new ArrayList<>(maps.keySet());
        StringBuilder strBuilder = new StringBuilder();
        keys.stream().sorted().forEach(o -> {
            strBuilder.append(o).append("=").append(maps.get(o)).append("&");
        });
        String decrypt = strBuilder.deleteCharAt(strBuilder.length() - 1).toString();
        return getSHA1(decrypt);
    }

    public static String getSHA1(String decrypt) throws DigestException {
        //获取信息摘要 - 参数字典排序后字符串
        try {
            //指定sha1算法
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(decrypt.getBytes());
            byte[] messageDigest = digest.digest();
            StringBuilder hexString = new StringBuilder();
            // 字节数组转换为 十六进制 数
            for (byte b : messageDigest) {
                String shaHex = Integer.toHexString(b & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString().toLowerCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new DigestException("签名错误！");
        }
    }

}